package ex01.pyrmont;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2023/4/27
 **/
public class HttpServer {
    //静态资源在这个目录下存放
    public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";
    //停止指令
    private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
    //停止标记
    private boolean shutdown = false;

    public static void main(String[] args) {
        HttpServer server = new HttpServer();
        server.await();
    }

    public void await() {
        ServerSocket serverSocket = null;
        int port = 8080;
        try {
            //请求进入连接队列的最大长度,服务端的 accept()方法会取出连接,该变量不设置默认为50
            serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        while (!shutdown) {
            Socket socket = null;
            InputStream input = null;
            OutputStream output = null;
            try {
                //接入客户端
                socket = serverSocket.accept();
                input = socket.getInputStream();
                output = socket.getOutputStream();

                //创建request解析入参
                Request request = new Request(input);
                request.parse();
                //通过入参判断是否是停止操作
                shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
                if (!shutdown) {
                    //如果不是停止操作则创建response
                    Response response = new Response(output);
                    response.setRequest(request);
                    //返回请求的资源
                    response.sendStaticResource();
                    socket.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
    }
}
